package com.qmrssreader.system;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.qmrssreader.dto.GroupItem;
import com.qmrssreader.dto.RssItem;
import com.qmrssreader.reader.QMRssReaderActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.widget.Toast;

import com.qmrssreader.reader.R;

public class NotifyService extends Service {

	private Long counter = 0L;
	private NotificationManager nm;
	private Timer timer = new Timer();
	private final Calendar time = Calendar.getInstance();

	PendingIntent contentIntent;
	Notification notification;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Toast.makeText(this, "Service created at " + time.getTime(),
				Toast.LENGTH_LONG).show();

		contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				QMRssReaderActivity.class), 0);

		//showNotification(0);
		incrementCounter();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// Cancel the persistent notification.
		shutdownCounter();
		nm.cancel(R.string.service_started);
		Toast.makeText(
				this,
				"Service destroyed at " + time.getTime() + "; counter is at: "
						+ counter, Toast.LENGTH_LONG).show();
		counter = null;
	}

	/**
	 * Show a notification while this service is running.
	 */
	private void showNotification(int id) {
		// In this sample, we'll use the same text for the ticker and the
		// expanded notification
		int noti_id = R.string.service_started;

		switch (id) {
		case 0:
			noti_id = R.string.service_started;
			break;
		case 1:
			noti_id = R.string.service_running;
			break;
		default:

		}
		CharSequence text = getText(noti_id);
		notification = new Notification(R.drawable.ic_72x72, text,
				System.currentTimeMillis());
		notification.setLatestEventInfo(this, getText(R.string.service_label),
				text, contentIntent);
		notification.sound=Uri.parse("android.resource://com.qmrssreader.reader/" + R.drawable.sasuke);
		nm.notify(noti_id, notification);
	}

	private void incrementCounter() {
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				counter++;
				if (newsUpdated()) {
					showNotification(1);
					//stopSelf();
				}
			}
		}, 0, CommonConfig.min_of_check*60000);
	}

	private void shutdownCounter() {
		if (timer != null) {
			timer.cancel();
		}
	}

	private boolean newsUpdated() {
		DBAdapter db = new DBAdapter(this);
		db.open();
		Cursor cursor = db.getAllRss1();
		//db.close();
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor
					.getColumnIndex(DBAdapter.KEY_NAME));
			String uri = cursor.getString(cursor
					.getColumnIndex(DBAdapter.KEY_LINK));
			if (name.startsWith("QM")) {
				// readMergedFeed(name, uri);
			} else {
				// readFromStorage(name, uri);

				ReallySimpleReader rssR = new ReallySimpleReader(uri);
				ArrayList<RssItem> newItems = rssR.getRSSItems1();
				if (newItems == null) {
					continue;
				} else {
					if (getOldDate(name).compareTo(rssR.getPubDate()) != 0) {
						db.close();
						return true;
					} else
						continue;
				}
			}
		}
		db.close();
		return false;
	}

	private Date getOldDate(String name) {
		try {
			FileInputStream istream = openFileInput(name);
			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();

			Document doc = builder.parse(istream);
			doc.getDocumentElement().normalize();
			Date date = new Date(doc
					.getElementsByTagName(CommonConfig.XML_ELEMENT_PUBDATE)
					.item(0).getTextContent());
			istream.close();
			return date;
		} catch (Exception e) {
			e.printStackTrace();
			return new Date();
		}
	}
}
